import { type UserConfig, type ConfigEnv, loadEnv, defineConfig } from "vite";
import uni from "@dcloudio/vite-plugin-uni";
import vueJsx from "@vitejs/plugin-vue-jsx";
import { resolve } from "path";
import AutoComponents from "unplugin-vue-components/vite";
import AutoImport from "unplugin-auto-import/vite";
import UniLayout from "@uni-helper/vite-plugin-uni-layouts";
import { UnifiedViteWeappTailwindcssPlugin as uvwt } from "weapp-tailwindcss/vite";
import dayjs from "dayjs";
import { visualizer } from "rollup-plugin-visualizer";
export default ({ mode }: ConfigEnv): UserConfig => {
  // console.log(mode === process.env.NODE_ENV) // true

  // pnpm dev:h5 时得到 => serve development
  // pnpm build:h5 时得到 => build production
  // pnpm dev:mp-weixin 时得到 => build development (注意区别，command为build)
  // pnpm build:mp-weixin 时得到 => build production
  // pnpm dev:app 时得到 => build development (注意区别，command为build)
  // pnpm build:app 时得到 => build production
  // dev 和 build 命令可以分别使用 .env.development 和 .env.production 的环境变量
  const root = process.cwd();
  const { UNI_PLATFORM } = process.env;
  const env = loadEnv(mode, root);
  const { VITE_APP_PORT, VITE_APP_BASE_URL, VITE_APP_PROXY } = env;
  return defineConfig({
    base: "./",
    build: {
      outDir: "dist",
      chunkSizeWarningLimit: 1500,
      rollupOptions: {
        output: {
          entryFileNames: `assets/[name].${new Date().getTime()}.js`,
          chunkFileNames: `assets/[name].${new Date().getTime()}.js`,
          assetFileNames: `assets/[name].${new Date().getTime()}.[ext]`,
          compact: true,
          // manualChunks: {
          //     vue: ['vue', 'vue-router', 'vuex'],
          //     echarts: ['echarts'],
          // },
        },
      },
    },

    resolve: {
      alias: [
        {
          find: "@",
          replacement: resolve(__dirname, "src"),
        },
      ],
    },
    server: {
      port: 1314,
      // 选项写法
      proxy: {
        "/lucky": {
          target: env.VITE_APP_BASE_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
        "/upload": {
          target: env.VITE_APP_BASE_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/upload/, ""),
        },
      },
    },
    plugins: [
      uni(),
      vueJsx(),
      uvwt({
        rem2rpx: true,
      }),
      AutoComponents({
        //自动导入组件
        dts: true,
        resolvers: [
          // example of importing Vant
          (componentName) => {
            if (componentName.startsWith("tm")) {
              return { name: componentName.slice(2), from: "tm" };
            }
          },
        ],
        dirs: [
          "./src/uni_modules/tm-ui/components",
          "src/components",
          "src/**/components",
        ],
        include: [/\.vue$/, /\.uvue$/],
      }),
      UniLayout(),
      // 自动导入
      AutoImport({
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/, // .vue
        ],
        imports: ["vue", "uni-app", "pinia"],
        dts: "typings/auto-imports.d.ts",
        dirs: ["src/hooks", "src/components", "src/**/components"],
        eslintrc: {
          enabled: true,
        },
      }),
      // h5环境增加 BUILD_TIME 和 BUILD_BRANCH
      UNI_PLATFORM === "h5" && {
        name: "html-transform",
        transformIndexHtml(html) {
          return html.replace(
            "%BUILD_TIME%",
            dayjs().format("YYYY-MM-DD HH:mm:ss")
          );
        },
      },
      // 打包分析插件，h5 + 生产环境才弹出
      UNI_PLATFORM === "h5" &&
        mode === "production" &&
        visualizer({
          filename: "./node_modules/.cache/visualizer/stats.html",
          open: true,
          gzipSize: true,
          brotliSize: true,
        }),
    ],
    css: {
      postcss: {
        plugins: [
          // require('tailwindcss')() 和 require('tailwindcss') 等价的，表示什么参数都不传，如果你想传入参数
          // require('tailwindcss')({} <- 这个是postcss插件参数)
          require("tailwindcss"),
          require("autoprefixer"),
        ],
      },
      preprocessorOptions: {
        scss: {
          api: "modern-compiler",
        },
      },
    },
    define: {
      __UNI_PLATFORM__: JSON.stringify(UNI_PLATFORM),
      __VITE_APP_PROXY__: JSON.stringify(VITE_APP_PROXY),
    },
  });
};
